package com.example.boke.controller.view;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.boke.entity.*;
import com.example.boke.mapper.*;
import com.example.boke.service.impl.*;
import com.example.boke.util.MarkdownUtils;
import com.example.boke.util.SortMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

@Controller
@RequestMapping(value = "/view")
public class viewcontroller {

    @Autowired
    private BlogServiceImpl blogServiceimpl;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private BlogTagServiceImpl blogTagServiceimpl;

    @Autowired
    private BlogTagMapper blogTagsMapper;

    @Autowired
    private TypeServiceImpl typeServiceimpl;

    @Autowired
    private TypeMapper typeMapper;

    private TagServiceImpl tagServiceimpl;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private UserServiceImpl userserviceimpl;

    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CommentServiceImpl commentserviceimpl;




    @GetMapping(value = "/about")
    public String about(Model model)
    {

        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();

        List<Type> types = typeMapper.selectList(typeQueryWrapper);

        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();

        List<Tag> tags = tagMapper.selectList(tagQueryWrapper);

        model.addAttribute("tags",tags);

        model.addAttribute("types",types);

        return "about";
    }



    @GetMapping(value = "/index")
    public String index(Model model,Integer pc)
    {

        if (pc == null)
        {
            pc = 1;
        }

        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();

        blogQueryWrapper.eq("published",true).orderByDesc("create_time");

        Integer blogcount = blogMapper.selectCount(blogQueryWrapper);

        Page<Blog> blogPage = new Page<>(pc, 5);

        blogMapper.selectPage(blogPage,blogQueryWrapper);

        List<Blog> blogList =  blogPage.getRecords();

        List<String> types = new ArrayList<>();

        QueryWrapper<BlogTag> blogTagQueryWrapper = new QueryWrapper<>();

        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();


        blogList.forEach(blog -> {

            Type type = typeMapper.selectById(blog.getTypeId());

            types.add(type.getName());

//            ----------------
            blogTagQueryWrapper.clear();

            blogTagQueryWrapper.eq("blogs_id",blog.getId());

            List<BlogTag> blogTagList = blogTagsMapper.selectList(blogTagQueryWrapper);

            blogTagList.forEach(blogTag -> {

                tagQueryWrapper.clear();

                tagQueryWrapper.eq("id", blogTag.getTagsId());

                Tag tag = tagMapper.selectOne(tagQueryWrapper);

                blog.addtag(tag);

            });

        });

        blogTagQueryWrapper.clear();

        tagQueryWrapper.clear();


        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        userQueryWrapper.eq("password",123456L);

        User user = userMapper.selectOne(userQueryWrapper);

        user.setPassword(null);

        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();

        typeQueryWrapper.eq("user_id", user.getId());

        List<Type> typeList = typeMapper.selectList(typeQueryWrapper);

        Map<String,Long> typemap = new HashMap<>();

        for (Type type : typeList) {

            blogQueryWrapper.clear();

            blogQueryWrapper.eq("user_id",user.getId()).eq("type_id",type.getId()).eq("published",true);

            //使得该类的id就是使用该分类的博客数量
            long aLong = blogMapper.selectCount(blogQueryWrapper);

            if (aLong != 0)
            {
                typemap.put(type.getName(), aLong);
            }

        }

        Map<String, Long> stringLongtypeMap = SortMap.sortDescend(typemap);

        tagQueryWrapper.eq("user_id",user.getId());

        List<Tag> tags = tagMapper.selectList(tagQueryWrapper);

        Map<String,Long> maptag = new HashMap<>();

        tags.forEach(tag -> {

            blogTagQueryWrapper.clear();

            blogTagQueryWrapper.eq("user_id",user.getId()).eq("tags_id",tag.getId()).orderByDesc("tags_id");

            long integer = blogTagsMapper.selectCount(blogTagQueryWrapper);

            if (integer != 0)
            {
                maptag.put(tag.getName(),integer);
            }

        });

        Map<String, Long> stringLongtagMap = SortMap.sortDescend(maptag);

        //获取最新推荐的五条博客
        blogQueryWrapper.clear();

        blogQueryWrapper.eq("user_id",user.getId()).eq("recommend",true).orderByDesc("create_time");
        Page<Blog> recommendblogPage = new Page<Blog>(0,5);

        blogMapper.selectPage(recommendblogPage,blogQueryWrapper);

        List<Blog> records = recommendblogPage.getRecords();

        records.forEach(blog -> {

            typeQueryWrapper.clear();

            typeQueryWrapper.eq("id",blog.getTypeId());

            Type type = typeMapper.selectOne(typeQueryWrapper);

            blog.setType(type);

//            -----------------------------

        });

        model.addAttribute("LatestRecommended",records);
        model.addAttribute("bloglist",blogList);
        model.addAttribute("typelist",types);
        model.addAttribute("user",user);
        model.addAttribute("stringLongtypeMap",stringLongtypeMap);
        model.addAttribute("stringLongtagMap",stringLongtagMap);
        model.addAttribute("blogcount",blogcount);
        model.addAttribute("pc",blogPage.getCurrent());
        model.addAttribute("hasPrevious",blogPage.hasPrevious());
        model.addAttribute("hasNext",blogPage.hasNext());

        return "index";
    }

    @GetMapping(value = "/tags")
    public String tags(Model model,String tagName,Integer pc)
    {
        if (pc == null)
        {
            pc = 1;
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        userQueryWrapper.eq("password",123456L);

        User user = userMapper.selectOne(userQueryWrapper);

        user.setPassword(null);


        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();

        tagQueryWrapper.eq("user_id", user.getId());

        List<Tag> tagList = tagMapper.selectList(tagQueryWrapper);

        Map<String,Long> tagmap = new HashMap<>();

        QueryWrapper<BlogTag> blogTagQueryWrapper = new QueryWrapper<>();

        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();

        int count = 0;

        for (Tag tag : tagList) {

            blogTagQueryWrapper.clear();

            blogTagQueryWrapper.eq("user_id",user.getId()).eq("tags_id",tag.getId());

            List<BlogTag> blogTags = blogTagsMapper.selectList(blogTagQueryWrapper);

            for (BlogTag blogTag : blogTags)
            {
                blogQueryWrapper.clear();

                blogQueryWrapper.eq("user_id",user.getId()).eq("id",blogTag.getBlogsId()).eq("published",true);

                count = count + blogMapper.selectCount(blogQueryWrapper);
            }

            tagmap.put(tag.getName(), (long) count);

            count = 0;
        }

        Map<String, Long> stringLongtagMap = SortMap.sortDescend(tagmap);

        if (tagName == null)
        {
            Iterator<Map.Entry<String, Long>> iterator = stringLongtagMap.entrySet().iterator();
            tagName = iterator.next().getKey();
        }

        tagQueryWrapper.clear();

        tagQueryWrapper.eq("name",tagName);

        Tag tag = tagMapper.selectOne(tagQueryWrapper);

        blogTagQueryWrapper.clear();

        blogTagQueryWrapper.eq("tags_id",tag.getId());

        //先找到该分类的全部博客

        List<BlogTag> blogTags = blogTagsMapper.selectList(blogTagQueryWrapper);

        //记录博客保存的数组
        List<Long> arrs = new ArrayList<Long>();


        for ( BlogTag blogTag : blogTags )
        {
            blogQueryWrapper.clear();

            blogQueryWrapper.eq("user_id",user.getId()).eq("id",blogTag.getBlogsId());

            Blog blog = blogMapper.selectOne(blogQueryWrapper);

            if ( !blog.getPublished() )
            {
                arrs.add(blog.getId());
            }

        }

        blogTagQueryWrapper.clear();

        blogTagQueryWrapper.eq("user_id",user.getId()).eq("tags_id",tag.getId());

        arrs.forEach(aLong -> {

            blogTagQueryWrapper.ne("blogs_id",aLong);

        });

        blogTagQueryWrapper.orderByDesc("id");

        Page<BlogTag> blogtagPage = new Page<>(pc,5);

        blogTagsMapper.selectPage(blogtagPage,blogTagQueryWrapper);

        List<BlogTag> records = blogtagPage.getRecords();

        List<Blog> blogs = new ArrayList<>();

        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();

        records.forEach(blogTag -> {

            blogQueryWrapper.clear();

            blogQueryWrapper.eq("id",blogTag.getBlogsId()).eq("published",true);

            Blog blog = blogMapper.selectOne(blogQueryWrapper);

            if (blog != null)
            {
                //获取该博客的分类以及标签
                typeQueryWrapper.clear();

                typeQueryWrapper.eq("user_id",user.getId()).eq("id",blog.getTypeId());

                Type type = typeMapper.selectOne(typeQueryWrapper);

                blog.setType(type);

                blogTagQueryWrapper.clear();

                blogTagQueryWrapper.eq("blogs_id",blog.getId()).eq("user_id",user.getId());

                List<BlogTag> blogTagList = blogTagsMapper.selectList(blogTagQueryWrapper);

                blogTagList.forEach(blogTag1 -> {

                    tagQueryWrapper.clear();

                    tagQueryWrapper.eq("id",blogTag1.getTagsId());

                    blog.addtag(tagMapper.selectOne(tagQueryWrapper));

                });

                blogs.add(blog);
            }

        });

        count = 0;

        for (String next : stringLongtagMap.keySet()) {

            count = Math.toIntExact(count + stringLongtagMap.get(next));

        }


        model.addAttribute("counttag",count);
        model.addAttribute("bloglist",blogs);
        model.addAttribute("user",user);
        model.addAttribute("stringLongtagMap",stringLongtagMap);
        model.addAttribute("tagName",tagName);
        model.addAttribute("pc",blogtagPage.getCurrent());
        model.addAttribute("hasPrevious",blogtagPage.hasPrevious());
        model.addAttribute("hasNext",blogtagPage.hasNext());

        return "tags";
    }

    @GetMapping(value = "/types")
    public String types(Model model,String typeName,Integer pc)
    {

        if (pc == null)
        {
            pc = 1;
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        userQueryWrapper.eq("password",123456L);

        User user = userMapper.selectOne(userQueryWrapper);

        user.setPassword(null);

        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();

        typeQueryWrapper.eq("user_id", user.getId());

        List<Type> typeList = typeMapper.selectList(typeQueryWrapper);

        Map<String,Long> typemap = new HashMap<>();

        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();

        for (Type type : typeList) {

            blogQueryWrapper.clear();

            blogQueryWrapper.eq("user_id",user.getId()).eq("type_id",type.getId()).eq("published",true);

            //使得该类的id就是使用该分类的博客数量
            long aLong = blogMapper.selectCount(blogQueryWrapper);

            if (aLong != 0)
            {
                typemap.put(type.getName(), aLong);
            }

        }

        Map<String, Long> stringLongtypeMap = SortMap.sortDescend(typemap);

        if (typeName == null)
        {
            Iterator<Map.Entry<String, Long>> iterator = stringLongtypeMap.entrySet().iterator();
            typeName = iterator.next().getKey();
        }

        typeQueryWrapper.clear();

        typeQueryWrapper.eq("name",typeName);

        Type type = typeMapper.selectOne(typeQueryWrapper);

        blogQueryWrapper.clear();

        blogQueryWrapper.eq("type_id",type.getId()) .eq("published",true).orderByDesc("create_time");

        Page<Blog> blogPage = new Page<>(pc, 5);

        blogMapper.selectPage(blogPage,blogQueryWrapper);

        List<Blog> records = blogPage.getRecords();

        QueryWrapper<BlogTag> blogTagQueryWrapper = new QueryWrapper<>();

        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();

        records.forEach(blog -> {

            blogTagQueryWrapper.clear();

            blogTagQueryWrapper.eq("blogs_id",blog.getId());

            List<BlogTag> blogTagList = blogTagsMapper.selectList(blogTagQueryWrapper);

            blogTagList.forEach(blogTag -> {

                tagQueryWrapper.clear();

                tagQueryWrapper.eq("id", blogTag.getTagsId());

                Tag tag = tagMapper.selectOne(tagQueryWrapper);

                blog.addtag(tag);

            });

        });

        int counttype = 0;

        for (String next : stringLongtypeMap.keySet())
        {

            counttype = Math.toIntExact(counttype + stringLongtypeMap.get(next));

        }

        model.addAttribute("counttype",counttype);
        model.addAttribute("bloglist",records);
        model.addAttribute("user",user);
        model.addAttribute("stringLongtypeMap",stringLongtypeMap);
        model.addAttribute("typeName",typeName);
        model.addAttribute("pc",blogPage.getCurrent());
        model.addAttribute("hasPrevious",blogPage.hasPrevious());
        model.addAttribute("hasNext",blogPage.hasNext());

        return "types";
    }

    @GetMapping(value = "/blogs")
    public String blogs(Long blogId,Model model){

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();

        userQueryWrapper.eq("password",123456L);

        User user = userMapper.selectOne(userQueryWrapper);

        user.setPassword(null);

        QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();

        blogQueryWrapper.eq("user_id",user.getId()).eq("id",blogId);

        Blog blog = blogMapper.selectOne(blogQueryWrapper);

        QueryWrapper<Type> typeQueryWrapper = new QueryWrapper<>();

        typeQueryWrapper.eq("user_id",user.getId()).eq("id",blog.getTypeId());

        Type type = typeMapper.selectOne(typeQueryWrapper);

        blog.setType(type);

        QueryWrapper<BlogTag> blogTagQueryWrapper = new QueryWrapper<>();

        blogTagQueryWrapper.eq("user_id",user.getId()).eq("blogs_id",blog.getId());

        List<BlogTag> blogTagList = blogTagsMapper.selectList(blogTagQueryWrapper);

        QueryWrapper<Tag> tagQueryWrapper = new QueryWrapper<>();

        blogTagList.forEach(blogTag -> {

            tagQueryWrapper.clear();

            tagQueryWrapper.eq("id",blogTag.getTagsId());

            Tag tag = tagMapper.selectOne(tagQueryWrapper);

            blog.addtag(tag);
        });

        String content = blog.getContent();
        content = MarkdownUtils.markdownToHtmlExtensions(content);

        blog.setContent(content);

        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();

        commentQueryWrapper.eq("superior_id",-1).eq("blog_id",blogId).orderByDesc("create_time");

        List<Comment> comments = commentMapper.selectList(commentQueryWrapper);

        model.addAttribute("blog",blog);
        model.addAttribute("user",user);
        model.addAttribute("comments",comments);
        return "blog";

    }


    @PostMapping(value = "/comment")
    public String comment(Comment comment,Model model){

        commentserviceimpl.save(comment);

        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();

        commentQueryWrapper.eq("superior_id",-1).eq("blog_id",comment.getBlogId()).orderByDesc("create_time");

        //这个是所有的父级评论
        List<Comment> comments = commentMapper.selectList(commentQueryWrapper);


        model.addAttribute("comments",comments);

        return "blog::commentList";

    }

    @PostMapping(value = "/rmovecomment")
    public String comment(Long commentId,Model model, Long blogId){

        commentMapper.deleteById(commentId);

        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();

        commentQueryWrapper.eq("superior_id",-1).eq("blog_id",blogId).orderByDesc("create_time");

        //这个是所有的父级评论
        List<Comment> comments = commentMapper.selectList(commentQueryWrapper);

        model.addAttribute("comments",comments);

        return "blog::commentList";

    }
}
